package kr.co.goodwilldd.framework.email;

import java.io.IOException;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import kr.co.goodwilldd.framework.email.model.EmailBody;
import kr.co.goodwilldd.framework.email.model.MailAttachment;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.ui.velocity.VelocityEngineFactory;
import org.springframework.ui.velocity.VelocityEngineUtils;

public class EmailListener implements ApplicationListener<ApplicationEvent> {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof EmailEvent) {
			EmailBody mailBody = (EmailBody) event.getSource();
			send(mailBody);
		}
	}

	private static final Logger logger = LoggerFactory
			.getLogger(EmailListener.class);

	@Autowired
	JavaMailSender mailSender;

	private VelocityEngine getVelocityEngine() throws IOException {
		VelocityEngineFactory vef = new VelocityEngineFactory();
		vef.setPreferFileSystemAccess(false);
		vef.setResourceLoaderPath("classpath:/mailTemplate/");
		return vef.createVelocityEngine();
	}

	private void send(final EmailBody mailBody) {
		try {
			mailSender.send(new MimeMessagePreparator() {
				public void prepare(MimeMessage mimeMessage) throws Exception {

					MimeMessageHelper message = new MimeMessageHelper(
							mimeMessage, true);
					message.setTo(mailBody.getToEmailAddresses());
					message.setFrom(new InternetAddress(mailBody
							.getFromEmailAddress()));
					message.setSubject(mailBody.getSubject());

					String body = VelocityEngineUtils.mergeTemplateIntoString(
							getVelocityEngine(), mailBody.getMailTemplate(),
							"UTF-8", mailBody.getParam());
					message.setText(body, true);
					if (mailBody.getAttachments() != null)
						for (MailAttachment attachment : mailBody
								.getAttachments()) {
							FileSystemResource file = new FileSystemResource(
									attachment.getAttachmentPath());
							message.addAttachment(
									attachment.getAttachmentName(), file);
						}
				}
			});
			if ( logger.isDebugEnabled() )
				logger.debug("email send success : {}", mailBody.toString());
		} catch (Exception e) {
			logger.warn("Please Check >>>>> kr.co.goodwilldd.framework.email.EmailListener <<<<< \n {}", mailBody.toString());
		}
	}
}
